import React, {useState, useEffect} from 'react';
import {withRouter} from 'react-router-dom';
import {Form} from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import {Select, Table, Tabs, Tooltip, message} from 'antd';
import moment from 'moment';
import {connect} from 'react-redux';

import {getRankPagesTable} from '~/service/performance';
import {
    PERFORMANCE_RANK_TABS, TIME_MEASURE_DATA, RANK_TARGET, RANK_MEASURE
} from '~/utils/const';
import {getDateRangeStr, getWeekRangeStr, popUpContainer} from '../utils';
import Header from './header';
import './index.styl';

const {TabPane} = Tabs;
const {Option} = Select;

function Rank(props) {
    const {match: {params: {id}}} = props;
    // redux search store
    const {searchParam} = props;
    const rankParam = searchParam.rank;
    // 业务线和应用的数据
    const [serviceLine, setServiceLine] = useState(rankParam.business);
    const [serviceLineList, setServiceLineList] = useState(rankParam.businessList);
    const [application, setApplication] = useState(rankParam.project);
    const [applicationList, setApplicationList] = useState(rankParam.projectList);

    // 时间段状态管理
    const [timeType, setTimeType] = useState(TIME_MEASURE_DATA[0].key);

    // 默认首屏时间
    const [targetType, setTargetType] = useState(1);
    // 默认平均值
    const [measureType, setMeasureType] = useState(1);

    // tab状态管理
    const [levelType, setLevelType] = useState(3);
    const {getFieldDecorator, setFieldsValue, resetFields} = props.form;
    const [loading, setLoading] = useState(false);
    const [dateRange, setDateRange] = useState([moment().subtract(1, 'day'), moment().subtract(1, 'day')]);
    const [rankList, setRankList] = useState([]);

    // 三期，需要点击搜索按钮后，才触发修改时刷新
    const [searched, setSearched] = useState(false);
    // 定义URL的样式
    function getContent(text, record, index) {
        return (
            <Tooltip title={text}>
                <div
                    style={{
                        maxWidth: 500, overflow: 'hidden', textOverflow: 'ellipsis',
                        whiteSpace: 'nowrap'
                    }}
                >
                    {text}
                </div>
            </Tooltip>
        );
    }
    // 性能排行表格表头
    const PERFORMANCE_RANK_TABLE_HEAD = [
        {
            title: '业务线',
            dataIndex: 'bizTypeName',
            key: 'bizTypeName_rank',
            align: 'left',
        },
        {
            title: '应用',
            dataIndex: 'bizName',
            key: 'bizName_rank',
            align: 'left',
        },
        {
            title: 'URL',
            dataIndex: 'path',
            key: 'path_rank',
            align: 'left',
            width: 500,
            render: getContent
        },
        {
            title: '时长',
            dataIndex: 'value',
            key: 'value_rank',
            align: 'left',
        }
    ];

    const getRankFun = async () => {
        if (!serviceLine || !application) {
            return;
        }
        setLoading(true);
        const [startTime, endTime]
        = timeType === TIME_MEASURE_DATA[0].key ? getDateRangeStr(dateRange) : getWeekRangeStr(dateRange);
        const data = await getRankPagesTable({
            targetType,
            bizTypeName: serviceLine,
            bizName: application,
            startTime,
            endTime,
            timeType,
            measureType,
            levelType,
            pageId: id
        });
        setRankList(data?.data?.measureRankDetails);
        setLoading(false);
    };
    function getRankList() {
        props.form.validateFields((error, fieldsValue) => {
            if (error) {
                return false;
            }
            setSearched(true);
            getRankFun();
        });
    }
    function getRowKey(record, index) {
        return index;
    }
    useEffect(() => {
        if (
            !serviceLine
            || !application
            || !targetType
            || !measureType
            || !searched
        ) {
            return;
        }
        setRankList([]);
        setLoading(true);
        getRankFun();
    }, [targetType, measureType, levelType]);

    function callback(key) {
        // setLoading(true);
        setLevelType(Number(key));
    }
    return (
        <div className="pages-performance-rank-container">
            <Form layout="inline">
                <Header
                    serviceLine={serviceLine}
                    serviceLineList={serviceLineList}
                    application={application}
                    applicationList={applicationList}
                    timeType={timeType}
                    setServiceLine={setServiceLine}
                    setServiceLineList={setServiceLineList}
                    setApplication={setApplication}
                    setApplicationList={setApplicationList}
                    setTimeType={setTimeType}
                    setDateRange={setDateRange}
                    getFieldDecorator={getFieldDecorator}
                    setFieldsValue={setFieldsValue}
                    getRankList={getRankList}
                    resetFields={resetFields}
                    setRankList={setRankList}
                />
                <div className="pages-performance-rank-content">
                    <span>指标标准:</span>
                    <Select
                        style={{width: 150}}
                        value={targetType}
                        className="first-screen-selector"
                        placeholder="指标类型"
                        onChange={setTargetType}
                        getPopupContainer={popUpContainer}
                    >
                        {RANK_TARGET.map(data => (
                            <Option key={data.key} value={data.key}>
                                {data.value}
                            </Option>
                        ))}
                    </Select>
                    <Select
                        style={{width: 150}}
                        value={measureType}
                        className="first-screen-selector"
                        placeholder="分位值"
                        onChange={setMeasureType}
                        getPopupContainer={popUpContainer}
                    >
                        {RANK_MEASURE.map(data => (
                            <Option key={data.key} value={data.key}>
                                {data.value}
                            </Option>
                        ))}
                    </Select>
                    <Tabs defaultActiveKey={levelType.toString()} onChange={callback} className="tab">
                        {PERFORMANCE_RANK_TABS.map(data => (
                            <TabPane tab={data.value} key={data.key}>
                                <Table
                                    columns={PERFORMANCE_RANK_TABLE_HEAD}
                                    dataSource={rankList}
                                    rowKey={getRowKey}
                                    loading={loading}
                                />
                            </TabPane>
                        ))}
                    </Tabs>
                </div>
            </Form>
        </div>
    );
}

export default connect(s => s)(Form.create({name: 'rankForm'})(withRouter(Rank)));
